package com.tange.ai.core.demo.add.ap;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.tange.ai.core.demo.LoginActivity;
import com.tange.ai.core.demo.Utils;
import com.tange.ai.core.demo.databinding.ActivityApNetworkConfigurationBinding;
import com.tange.ai.core.demo.databinding.ActivityWifiConfigurationBinding;
import com.tange.core.backend.service.http.HttpConfigurations;
import com.tange.core.backend.service.request.Http;
import com.tange.core.backend.service.request.HttpResponse;
import com.tange.core.backend.service.response.RxResponse;
import com.tange.module.add.configure.DeviceApNetworkConfigure;
import com.tange.module.add.connect.DeviceApConnect;
import com.tange.module.add.match.DeviceMatchQuery;
import com.tg.data.http.entity.DeviceMatchBean;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 设备配网
 */
public class DeviceNetworkConfigurationActivity extends AppCompatActivity {

    private ActivityApNetworkConfigurationBinding binding;

    private String deviceApName;
    private String wifiName;
    private String wifiPwd;

    private String status = "";

    private final Handler handler = new Handler(Looper.getMainLooper());

    private DeviceApNetworkConfigure deviceApNetworkConfigure;
    private DeviceApConnect deviceApConnect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityApNetworkConfigurationBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getSupportActionBar().hide();

        Utils.setStatusBar(this, Color.TRANSPARENT);

        deviceApName = getIntent().getStringExtra(WiFiConfigurationActivity.DEVICE_AP_NAME);
        wifiName = getIntent().getStringExtra(WiFiConfigurationActivity.WIFI_NAME);
        wifiPwd = getIntent().getStringExtra(WiFiConfigurationActivity.WIFI_PASSWORD);

        binding.next.setOnClickListener(view -> {

            binding.next.setEnabled(false);

            // 1. 将手机连接至设备的AP
            connectDeviceAp();

        });
    }

    private void connectDeviceAp() {

        status = status + "\n" + "开始连接至设备热点：" + deviceApName + " ...";
        binding.statusTv.setText(status);


        deviceApConnect = DeviceApConnect.create(this, deviceApName, "", new DeviceApConnect.Callback() {
            @Override
            public void onConnected() {
                status = status + "\n" + "设备热点连接成功！";
                status = status + "\n" + "向设备发送配网信息 ...";
                binding.statusTv.setText(status);

                sendNetworkConfigurations();
            }

            @Override
            public void onScanned(boolean isApPasswordRequired) {
                status = status + "\n" + "扫描到了对应的设备热点，是否需要密码 = " + isApPasswordRequired;
                binding.statusTv.setText(status);

                Toast.makeText(DeviceNetworkConfigurationActivity.this, "此AP需要密码！请修改Demo源码去传递密码", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int errorCode) {
                status = status + "\n" + "设备热点连接失败！ 错误码 = " + errorCode;
                binding.statusTv.setText(status);
            }
        });
        deviceApConnect.start();
    }

    private void sendNetworkConfigurations() {
        status = status + "\n" + "开始向设备发送配网信息 ...";
        binding.statusTv.setText(status);

        deviceApNetworkConfigure = DeviceApNetworkConfigure.create(this,
                HttpConfigurations.getInstance().userId(),
                deviceApName,
                "null",
                wifiName,
                wifiPwd,
                new DeviceApNetworkConfigure.Callback() {
                    @Override
                    public void onSuccess(String bindToken) {
                        status = status + "\n" + "发送成功！";
                        status = status + "\n" + "开始查询设备配网结果 ...";
                        binding.statusTv.setText(status);

                        queryDeviceMatching(bindToken);
                    }

                    @Override
                    public void onFailed(int errorCode) {
                        status = status + "\n" + "发送失败！" + errorCode;
                        binding.statusTv.setText(status);
                    }
        });
        deviceApNetworkConfigure.send();
    }

    private void queryDeviceMatching(String bindToken) {
        DeviceMatchQuery.create().request(bindToken, new DeviceMatchQuery.Callback() {
            @Override
            public void onSuccess(DeviceMatchBean deviceMatchBean) {
                // 设备配网成功，继续后续业务逻辑，比如设置设备名称
                status = status + "\n" + "设备配网成功！ID = " + deviceMatchBean.getId();
                binding.statusTv.setText(status);

                updateDeviceName(deviceMatchBean.getId());
            }

            @Override
            public void onError(int errorCode, String errorMsg) {
                // 尚未配网成功
                status = status + "\n" + "查询失败 " + errorCode + ", " + errorMsg + ", 5s后再次查询 ...";
                binding.statusTv.setText(status);

                handler.postDelayed(() -> queryDeviceMatching(bindToken), 5000);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (deviceApNetworkConfigure != null) {
            deviceApNetworkConfigure.destroy();
        }

        if (deviceApConnect != null) {
            deviceApConnect.destroy();
        }

        handler.removeCallbacksAndMessages(null);
    }

    private void updateDeviceName(long deviceId) {
        status = status + "\n" + "尝试修改设备名称...";
        String name = "我是AP添加的";
        binding.statusTv.setText(status);
        Http.INSTANCE.create()
                .path("/device/alter")
                .param("device_id", deviceId)
                .param("name", name)
                .post()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HttpResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HttpResponse response) {
                        if (response.isSuccess()) {
                            status = status + "\n" + "修改设备名称成功";
                            status = status + "\n" + "名称修改为\"" + name + "\"";
                            binding.statusTv.setText(status);
                        } else {
                            status = status + "\n" + "修改设备名称失败";
                            binding.statusTv.setText(status);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        status = status + "\n" + "修改设备名称失败";
                        binding.statusTv.setText(status);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}